package com.Framework.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.PasswordAuthentication;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.Framework.Entity.MailEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


public class Tools {

	
	public enum SysteamObjectType {
		String(1, "String"), Int(2, "Int"), BigDecimal(3, "BigDecimal")
		, Long(4, "Long"), Date(5, "Date"), Timestamp(6,"Timestamp")
		, Double(7, "Double"), Md5(8, "Md5"), YYYYMMDDHHmmSSS(9, "YYYYMMDDHHmmSSS")
		, YYYYMMDDHHmmSS(10, "YYYYMMDDHHmmSS"), YYYYMMDDHHmm(11, "YYYYMMDDHHmm")
		, YYYYMMDDHH(12,"YYYYMMDDHH"), YYYYMMDD(13, "YYYYMMDD"), YYYYMM(14, "YYYYMM")
		, YYYY(15, "YYYY"), MM(16,"MM"), DD(17, "DD"), HH(18, "HH")
		, mm(19, "mm"), SS(20, "SS"), XML(21,"XML"), XMLReplace(22, "XMLReplace")
		, Systime2Week(23, "Systime2Week"),Jason(24, "Jason")
		;

		private int index;
		private String name;

		private SysteamObjectType(int index, String name) {
			this.name = name;
			this.index = index;
		}

		public static String getNameByIndex(int index) {
			for (SysteamObjectType c : SysteamObjectType.values()) {
				if (c.getIndex() == index) {
					return c.name;
				}
			}
			return null;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}
	}

	public enum FileCoding {
		UTF8(1, "utf-8"), GBK(1, "gbk"),;

		private int index;
		private String name;

		private FileCoding(int index, String name) {
			this.name = name;
			this.index = index;
		}

		public static String getNameByIndex(int index) {
			for (FileCoding c : FileCoding.values()) {
				if (c.getIndex() == index) {
					return c.name;
				}
			}
			return null;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getIndex() {
			return index;
		}

		public void setIndex(int index) {
			this.index = index;
		}
	}
	

	public static class BeanTools {

		/**
		 * @author yz
		 * @title Bean转Map
		 * @version v1.0
		 * @date 2017年8月2日 上午11:54:37
		 * @param bean
		 * @return
		 * @remark
		 */
		public static Map<String, String> bean2Map(Object bean) {
			System.out.println("3.1");
			String jason = JasonTools.object2JsonStr(bean);
			System.out.println("3.3");
			return JasonTools.jason2Map(jason);
		}

		/**
		 * @author yz
		 * @title Bean转jason
		 * @version v1.0
		 * @date 2017年8月2日 上午11:54:37
		 * @param bean
		 * @return
		 * @remark
		 */
		public static String bean2Jason(Object bean) {
			String jason = JasonTools.object2JsonStr(bean);
			return jason;
		}

		/**
		 * @author yz
		 * @title Map转Bean
		 * @version v1.0
		 * @date 2017年8月2日 上午11:54:37
		 * @param bean
		 * @return
		 * @remark
		 */
		public static Object map2Bean(Map map, Class clazz) {
			String jason = JasonTools.object2JsonStr(map);
			return JasonTools.jason2Bean(jason, clazz);
		}

		/**
		 * @author yz
		 * @title jason字符串转对象
		 * @version v1.0
		 * @date 2017年8月2日 上午11:43:04
		 * @param bean
		 * @param jasonVal
		 * @return
		 * @remark
		 */
		public static Object jason2Bean(String jasonStr, Object bean) {
			return JSON.parseObject(jasonStr, bean.getClass());
		}

	}

	public static class JasonTools {

		/**
		 * @author yz
		 * @title 任意对象转Jason
		 * @version v1.0
		 * @date 2017年8月2日 上午11:54:17
		 * @param obj
		 * @return
		 * @remark
		 */
		public static String object2JsonStr(Object obj) {
			String mes=JSON.toJSONString(obj);
			return mes;			
		}

		/**
		 * @author yz
		 * @title jason转map
		 * @version v1.0
		 * @date 2017年8月2日 上午11:56:13
		 * @param bean
		 * @return
		 * @remark
		 */
		public static Map<String, String> jason2Map(String jasonStr) {
			return JSON.parseObject(jasonStr, Map.class);
		}

		/**
		 * @author yz
		 * @title jason转bean
		 * @version v1.0
		 * @date 2017年8月2日 下午12:01:36
		 * @param jasonStr
		 * @param obj
		 * @return
		 * @remark
		 */
		public static Object jason2Bean(String jasonStr, Class clazz) {
			return JSON.parseObject(jasonStr, clazz);
		}

	}

	public static class ObjectTools {

		public static int compareDate(String DATE1, String DATE2) {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				Date dt1 = df.parse(DATE1);
				Date dt2 = df.parse(DATE2);
				if (dt1.getTime() > dt2.getTime()) {
					// System.out.println("dt1 在dt2前");
					return 1;
				} else if (dt1.getTime() < dt2.getTime()) {
					// System.out.println("dt1在dt2后");
					return -1;
				} else {
					return 0;
				}
			} catch (Exception exception) {
				exception.printStackTrace();
			}
			return 0;
		}

		public static Object object2Object(Object obj, SysteamObjectType systeamObjectType) throws Exception {
			if (null != obj) {
				String returnMes = obj.toString();
				if (SysteamObjectType.String.equals(systeamObjectType)) {
					return returnMes;
				} else if (SysteamObjectType.Int.equals(systeamObjectType)) {
					return Integer.parseInt(returnMes);
				} else if (SysteamObjectType.BigDecimal.equals(systeamObjectType)) {
					return new BigDecimal(returnMes);
				} else if (SysteamObjectType.Long.equals(systeamObjectType)) {
					return Long.valueOf(returnMes).longValue();
				} else if (SysteamObjectType.Double.equals(systeamObjectType)) {
					return Double.valueOf(returnMes);
				} else if (SysteamObjectType.Date.equals(systeamObjectType)) {
					if (returnMes.indexOf("-") > -1) {
						if (returnMes.length() == 10) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							return sdf.parse(returnMes);
						} else if (returnMes.length() == 19) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							return sdf.parse(returnMes);
						}
					} else if (returnMes.indexOf("/") > -1) {
						if (returnMes.length() == 10) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
							return sdf.parse(returnMes);
						} else if (returnMes.length() == 19) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
							return sdf.parse(returnMes);
						}
					}
				} else if (SysteamObjectType.Timestamp.equals(systeamObjectType)) {
					if (returnMes.length() == 10) {
						returnMes += " 00:00:00";
					}

					if (returnMes.indexOf("/") > -1) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
						return String.valueOf(sdf.parse(returnMes).getTime() / 1000);
					} else if (returnMes.indexOf("-") > -1) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						return String.valueOf(sdf.parse(returnMes).getTime() / 1000);
					}

				} else if (SysteamObjectType.Md5.equals(systeamObjectType)) {
					StringBuffer sb = new StringBuffer(32);
					MessageDigest md = MessageDigest.getInstance("MD5");
					md.update(returnMes.getBytes("utf-8"));
					byte[] array = md.digest();
					for (int i = 0; i < array.length; i++) {
						sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
					}
					return sb.toString();
				} else if (SysteamObjectType.YYYYMMDDHHmmSSS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYYMMDDHHmmSS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYYMMDDHHmm.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYYMMDDHH.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYYMMDD.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYYMM.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
					return df.format(returnMes);
				} else if (SysteamObjectType.YYYY.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy");
					return df.format(returnMes);
				} else if (SysteamObjectType.MM.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("MM");
					return df.format(returnMes);
				} else if (SysteamObjectType.DD.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("DD");
					return df.format(returnMes);
				} else if (SysteamObjectType.HH.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("HH");
					return df.format(returnMes);
				} else if (SysteamObjectType.mm.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("mm");
					return df.format(returnMes);
				} else if (SysteamObjectType.SS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("SS");
					return df.format(returnMes);
				} else if (SysteamObjectType.XML.equals(systeamObjectType)) {
					boolean bs = false;
					if (returnMes.indexOf(">") != -1) {
						bs = true;
					} else if (returnMes.indexOf("<") != -1) {
						bs = true;
					} else if (returnMes.indexOf("&") != -1) {
						bs = true;
					} else if (returnMes.indexOf("\"") != -1) {
						bs = true;
					} else if (returnMes.indexOf(",") != -1) {
						bs = true;
					}
					if (bs) {
						returnMes = "<![CDATA[" + returnMes + "]]>";
					}
					return returnMes;
				} else if (SysteamObjectType.XMLReplace.equals(systeamObjectType)) {
					returnMes = returnMes.replace(">", "&gt;");
					returnMes = returnMes.replace("<", "&lt;");
					returnMes = returnMes.replace("&", "&amp;");
					returnMes = returnMes.replace("\"", "&quot;");
					returnMes = returnMes.replace("'", "&apos;");
				} else if (SysteamObjectType.Jason.equals(systeamObjectType)) {
					JSON json = (JSON) JSON.toJSON(returnMes);
					return json.toString();
				}
			} else {
				if (SysteamObjectType.YYYYMMDDHHmmSSS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYYMMDDHHmmSS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYYMMDDHHmm.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYYMMDDHH.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYYMMDD.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYYMM.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
					return df.format(new Date());
				} else if (SysteamObjectType.YYYY.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy");
					return df.format(new Date());
				} else if (SysteamObjectType.MM.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("MM");
					return df.format(new Date());
				} else if (SysteamObjectType.DD.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("DD");
					return df.format(new Date());
				} else if (SysteamObjectType.HH.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("HH");
					return df.format(new Date());
				} else if (SysteamObjectType.mm.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("mm");
					return df.format(new Date());
				} else if (SysteamObjectType.SS.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("SS");
					return df.format(new Date());
				} else if (SysteamObjectType.Systime2Week.equals(systeamObjectType)) {
					SimpleDateFormat df = new SimpleDateFormat("EEEE");
					return df.format(new Date());
				}
			}
			return null;
		}

		public static int getMonthlydays(int _year, int _month) {
			Calendar a = Calendar.getInstance();
			a.set(Calendar.YEAR, _year);
			a.set(Calendar.MONTH, _month - 1);
			a.set(Calendar.DATE, 1);
			a.roll(Calendar.DATE, -1);
			int maxDate = a.get(Calendar.DATE);
			return maxDate;
		}

		public static boolean checkNumber(String data) throws Exception {
			boolean bs = true;
			data = "" + data;
			for (int i = 0; i < data.length(); i++) {
				String key = data.substring(i, i + 1);
				if ("0123456789.-".indexOf(key) == -1) {
					bs = false;
				}
			}

			if (bs) {
				String[] ls = data.split("-");
				String[] ls2 = data.split(".");
				if (ls.length > 2 || ls2.length > 2) {
					bs = false;
				}
			}
			return bs;
		}
		
		public static String getRandom(int length) throws Exception {
			String sRs = "";
			Random random = new Random();
			String[] keys = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
			for (int i = 0; i < length; i++) {
				sRs = sRs + keys[random.nextInt(36)];
			}
			return sRs;
		}

		public static String getSubstring(String mes, String strat, String end) throws Exception {
			String mes1 = (mes.substring(mes.indexOf(strat), mes.length())).replaceFirst(strat, "");
			String mes2 = mes1.substring(0, mes1.indexOf(end));
			return mes2;
		}

		public static String getTimeAmPm(String ampm) throws Exception {
			if (ampm.contains("am")) {
				return ampm.substring(0, ampm.indexOf("am"));
			} else if (ampm.contains("pm")) {
				int i = ampm.indexOf(":");
				String s = ampm.substring(0, i);
				int hour = Integer.parseInt(s);
				if (hour >= 12) {
					String res = ampm.substring(0, ampm.indexOf("pm"));
					return res;
				} else {
					String sHour = hour + 12 + "";
					return sHour + ampm.substring(ampm.indexOf(":"), ampm.indexOf("pm"));
				}
			} else {
				return ampm;
			}

		}

		public static String getSex(String identityNo) throws Exception {
			String sex = "";
			if (identityNo.length() == 15) {
				String mes = identityNo.substring(identityNo.length() - 1, identityNo.length());
				if (("1,3,5,7,9").indexOf(mes) > -1) {
					sex = "男";
				} else {
					sex = "女";
				}
			} else if (identityNo.length() == 18) {
				String mes = identityNo.substring(identityNo.length() - 2, identityNo.length() - 1);
				if (("1,3,5,7,9").indexOf(mes) > -1) {
					sex = "男";
				} else {
					sex = "女";
				}
			}
			return sex;
		}
	}

	public static class FileTools {
		
		public static synchronized boolean publicisExists(Object file) {
			if (file instanceof String) {
				File folder = new File((String) file);
				if (folder.exists()) {
					return true;
				}
			} else if (file instanceof File) {
				if (((File) file).exists()) {
					return true;
				}
			}
			return false;
		}

		public static synchronized boolean publicisFile(Object file) {
			if (file instanceof String) {
				File folder = new File((String) file);
				if (folder.isFile()) {
					return true;
				}
			} else if (file instanceof File) {
				if (((File) file).isFile()) {
					return true;
				}
			}
			return false;
		}

		public static synchronized boolean publicisDirectory(Object file) {
			if (file instanceof String) {
				File folder = new File((String) file);
				if (folder.isDirectory()) {
					return true;
				}
			} else if (file instanceof File) {
				if (((File) file).isDirectory()) {
					return true;
				}
			}
			return false;
		}

		public static class XmlTools {

			public static synchronized NodeList getNodeList(String fileRelativeAddress, String tagName)
					throws Exception {
				// 检测地址
				String filePath = fileRelativeAddress;
				NodeList bookList = null;
				

				if (CheckTools.checkNotEmpty(filePath)) {
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();
					Document document = db.parse(filePath);
					bookList = document.getElementsByTagName(tagName);
				}
				return bookList;
			}

			public static synchronized String getAttributes(String fileRelativeAddress, String tagName, String keyName,
					String keyValue, String attrName) throws Exception {
				String values = "";

				// 检测地址
				String filePath = fileRelativeAddress;
			
				if (CheckTools.checkNotEmpty(filePath)) {
					DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
					DocumentBuilder db = dbf.newDocumentBuilder();
					Document document = db.parse(filePath);
					NodeList bookList = document.getElementsByTagName(tagName);
					for (int i = 0; i < bookList.getLength(); i++) {
						Node book = bookList.item(i);
						NamedNodeMap attrs = book.getAttributes();
						boolean bs = false;
						for (int j = 0; j < attrs.getLength(); j++) {
							Node attr = attrs.item(j);
							if (attr.getNodeName().equals(keyName)) {
								if (attr.getNodeValue().equals(keyValue)) {
									bs = true;
									break;
								}
							}
						}

						if (bs) {
							for (int j = 0; j < attrs.getLength(); j++) {
								Node attr = attrs.item(j);
								if (attr.getNodeName().equals(attrName)) {
									values = attr.getNodeValue();
									break;
								}
							}
							break;
						}
					}
				} else {
					System.out.println("路径为空,请初始化:" + filePath);
				}
				return values;
			}
		}

		public static class PropertiesTools {

			public static synchronized String getProperties(String key) {
				InputStream inStream = Tools.class.getClassLoader().getResourceAsStream("PhonenixConf.properties");
				Properties prop = new Properties();
				try {
					prop.load(inStream);
					return prop.getProperty(key);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return null;
			}
		}

		public static class DefaultTools {
			public static synchronized boolean createFile(String relativeAddress) {
				boolean bs = false;
				try {
					String fullUrl = relativeAddress;
					fullUrl = fullUrl.replace("//", "/");
					String[] mes_h = fullUrl.toString().split("/");
					String mes_h_l = "";

					if (CheckTools.checkEmpty(mes_h)) {
						System.out.println("文件地址为空");
						return false;
					}

					for (int i = 0, len = mes_h.length; i < len; i++) {// 循环创建文件夹
						mes_h_l += "/" + mes_h[i].toString();
						if (!FileTools.publicisExists(mes_h_l)) {
							if (mes_h[i].toString().indexOf(".") > -1) {
								File file = new File(mes_h_l);
								file.createNewFile();// 创建文件
								bs = true;
							} else {
								File folder = new File(mes_h_l);
								folder.mkdir();// 创建文件夹
								bs = true;
							}
						}
					}
				} catch (Exception e) {
					bs = false;
					System.out.println("创建文件夹异常：");
					System.out.println("==========>：" + e.getMessage().toString());
				}
				return bs;
			}

			public static synchronized boolean deleteFile(String relativeAddress) {
				boolean bs = false;
				try {

					String folder_url = relativeAddress;

					File directory = new File("");// 设定为当前文件夹
					String _url = directory.getCanonicalPath().toString();
					_url = _url + folder_url;
					File file = new File(_url);
					if (file.exists()) { // 判断文件是否存在
						if (file.isFile()) { // 判断是否是文件
							file.delete(); // delete()方法 你应该知道 是删除的意思;
						} else if (file.isDirectory()) { // 否则如果它是一个目录
							File files[] = file.listFiles(); // 声明目录下所有的文件
																// files[];
							for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
								deleteFile(folder_url + "/" + files[i].toString()); // 把每个文件
																					// 用这个方法进行迭代
							}
						}
						file.delete();
						bs = true;
					} else {
						System.out.println("所删除的文件夹不存在！" + '\n');
					}
				} catch (Exception e) {
					bs = false;
					System.out.println("删除文件夹异常：");
					System.out.println("==========>：" + e.getMessage().toString());
				}
				return bs;
			}

			public static synchronized String readFile(String relativeAddress, FileCoding fileCoding) {
				StringBuffer bf = new StringBuffer();
				try {
					String file_url = relativeAddress;
					BufferedReader br = null;
					String _readmes = new String();
					File _file = new File(file_url);
					br = new BufferedReader(new FileReader(_file));
					while ((_readmes = (br.readLine())) != null) {
						_readmes = new String(_readmes.getBytes("ISO-8859-1"), fileCoding.getName());
						bf = bf.append(_readmes).append("\r");
					}
					br.close();
				} catch (Exception e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				} finally {
				}
				return bf.toString();
			}

			public static synchronized void writeFileWhithBufferedWriter(String relativeAddress, String str_content) {
				// 先读取原有文件内容，然后进行写入操作
				boolean _bs = false;
				BufferedWriter fw = null;
				String file_url = "";
				try {
					file_url = relativeAddress;
					file_url = file_url.replace("//", "/");
					File _file = new File(file_url);
					fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_file, true), "UTF-8")); // 指定编码格式，以免读取时中文字符异常
					fw.append(str_content);
					fw.flush(); // 全部写入缓存中的内容
					_bs = true;
				} catch (Exception e) {
					// TODO 自动生成 catch 块
					e.printStackTrace();
				} finally {
					if (fw != null) {
						try {
							fw.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

				if (_bs) {
					System.out.println("文件写入成功：" + file_url);
				} else {
					System.out.println("文件写入失败:" + file_url);
				}
			}

			public static synchronized void writeFileWhithFileWriter(String relativeAddress, String str_content) {
				// 先读取原有文件内容，然后进行写入操作
				boolean _bs = false;
				FileWriter writer = null;
				String file_url = "";
				try {

					file_url = relativeAddress;
					file_url = file_url.replace("//", "/");
					// 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件,false表示覆盖的方式写入
					writer = new FileWriter(file_url, false);
					if (CheckTools.checkNotEmpty(str_content)) {
						writer.write(str_content);
					}
					_bs = true;
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (writer != null) {
							writer.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				if (_bs) {
					System.out.println("文件写入成功：" + file_url);
				} else {
					System.out.println("文件写入失败:" + file_url);
				}
			}

			public static synchronized boolean copyFile(String oldpath, String newpath) {
				boolean _bs = false;
				try {
					int bytesum = 0;
					int byteread = 0;
					File oldfile = new File(oldpath);
					if (oldfile.exists()) { // 文件存在时
						InputStream inStream = new FileInputStream(oldpath); // 读入原文件
						FileOutputStream fs = new FileOutputStream(newpath);
						byte[] buffer = new byte[2048];
						int length;
						while ((length = inStream.read(buffer)) != -1) {
							fs.write(buffer, 0, length);
						} // 字节数 文件大小
						inStream.close();
						fs.flush();
						fs.close();
						_bs = true;
					}
				} catch (Exception e) {
					System.out.println("复制单个文件操作出错");
					e.printStackTrace();
				}
				return _bs;
			}

			public static synchronized boolean keepfiles(String file_url, int savecounts) {

				boolean bs = false;
				try {
					File directory = new File("");// 设定为当前文件夹
					String _url = directory.getCanonicalPath().toString();
					_url = _url + file_url;
					File file = new File(_url);
					File[] files = file.listFiles();
					List _list = new ArrayList();
					if (files != null) {
						if (files.length > 0) {
							// Arrays.sort(files);//排序
							// 按日期排序
							Arrays.sort(files, new Comparator<File>() {
								public int compare(File f1, File f2) {
									long diff = f1.lastModified() - f2.lastModified();
									if (diff > 0) {
										return 1;
									} else if (diff == 0) {
										return 0;
									} else {
										return -1;
									}
								}

								public boolean equals(Object obj) {
									return true;
								}
							});
							for (int kk = 0; kk < files.length; kk++) {
								if (!files[kk].isDirectory()) {
									String str_mes = files[kk].toString();
									_list.add(str_mes);
								}
							}
						}
					}

					if (_list.size() > savecounts) {
						for (int i = 0, m = _list.size(); i < m - savecounts; i++) {
							String fil = _list.get(i).toString();
							File ff = new File(fil);
							ff.delete();
							try {
								Thread.sleep(50);
							} catch (Exception e) {
							}
						}
					}
				} catch (Exception e) {
					System.out.println("复制单个文件操作出错");
					e.printStackTrace();
				}
				return bs;
			}
		}
	}

	public static class CheckTools {
		public static boolean checkNotEmpty(Object obj) {
			return !checkEmpty(obj);
		}
		
		public static boolean checkNotEmpty(Object obj,String keyName) {
			return !checkEmpty(obj,keyName);
		}

		// 校验空 true 空 ,false 非空
		public static boolean checkEmpty(Object obj) {
			if (null == obj) {// 直接空
				return true;
			} else {// 非空
				if (obj instanceof Integer) {
					int it = ((Integer) obj).intValue();
					if (("" + it).length() > 0) {
						return false;
					}
				} else if (obj instanceof String) {
					String s = (String) obj;
					if (("" + s).length() > 0) {
						return false;
					}
				} else if (obj instanceof Double) {
					double d = ((Double) obj).doubleValue();
					if (("" + d).length() > 0) {
						return false;
					}
				} else if (obj instanceof Float) {
					float f = ((Float) obj).floatValue();
					if (("" + f).length() > 0) {
						return false;
					}
				} else if (obj instanceof Long) {
					long l = ((Long) obj).longValue();
					if (("" + l).length() > 0) {
						return false;
					}
				} else if (obj instanceof Boolean) {
					boolean b = ((Boolean) obj).booleanValue();
					if (("" + b).length() > 0) {
						return false;
					}
				} else if (obj instanceof Map) {
					Map m = (Map) obj;
					if (!m.isEmpty()) {
						return false;
					}
				} else if (obj instanceof HashMap) {
					HashMap m = (HashMap) obj;
					if (!m.isEmpty()) {
						return false;
					}
				} else if (obj instanceof List) {
					List l = (List) obj;
					if (l.size() > 0) {
						return false;
					}
				} else if (obj instanceof ArrayList) {
					ArrayList al = (ArrayList) obj;
					if (al.size() > 0) {
						return false;
					}
				} else if (obj instanceof String[]) {
					String[] al = (String[]) obj;
					if (al.length > 0) {
						return false;
					}
				} else if (obj instanceof Connection) {
					if (obj != null) {
						return false;
					}
				} else if (obj instanceof Timestamp) {
					if (obj != null) {
						return false;
					}
				} else if (obj instanceof BigDecimal) {
					if (obj != null) {
						return false;
					}
				} else if (obj instanceof FileCoding) {
					if (obj != null) {
						return false;
					}
				} else {
					if (obj != null) {
						System.out.println("Warning:未能识别此类型请扩展" + obj.getClass().getName() + "");
						return false;
					}
				}
				return true;
			}
		}
		
		public static boolean checkEmpty(Object obj,String keyName) {
			if (null == obj) {// 直接空
				return true;
			} else {// 非空
			    if (obj instanceof Map) {
					Map m = (Map) obj;
					if (!m.isEmpty()) {
						if(m.containsKey(keyName)){
							Object obj2=m.get(keyName);
							if(obj2==null||obj2.toString().trim().length()==0){
								return true;
							}else{
								return false;
							}							
						}else{
							return true;
						}					
					}
				} else if (obj instanceof HashMap) {
					HashMap m = (HashMap) obj;
					if (!m.isEmpty()) {
						return false;
					}
				} else {
					if (obj != null) {
						System.out.println("Warning:未能识别此类型请扩展" + obj.getClass().getName() + "");
						return false;
					}
				}
				return true;
			}
		}

	}

	public static class DBTools {

		private static Connection dbConn = null;
		private static PreparedStatement ps = null;
		private static ResultSet rs = null;
		private static ResultSetMetaData rsd = null;

		private static synchronized void close() throws Exception {
			Object[] param = new Object[] { ps, rs, rsd, dbConn };
			if (param != null) {
				for (Object obj : param) {
					try {
						if ((obj instanceof ResultSet)) {
							((ResultSet) obj).close();
							obj = null;
						}
						if ((obj instanceof PreparedStatement)) {
							((PreparedStatement) obj).close();
							obj = null;
						}

						if ((obj instanceof Statement)) {
							((Statement) obj).close();
							obj = null;
						}

						if ((obj instanceof Connection)) {
							((Connection) obj).close();
							obj = null;
						}
						if ((obj instanceof BufferedReader)) {
							((BufferedReader) obj).close();
							obj = null;
						}

						if ((obj instanceof ResultSetMetaData)) {
							obj = null;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		private static synchronized boolean ini(String dbKey) throws Exception {

			boolean bs = false;
			if (CheckTools.checkNotEmpty(dbConn)) {
				if (!dbConn.isClosed()) {
					close();
				}
			}
			if (dbConn != null) {
				if (!dbConn.isClosed()) {
					close();
				}
			}
			try {
				String driver = FileTools.XmlTools.getAttributes(null, "DbConfig", "key", dbKey, "driver");

				String connUrl = FileTools.XmlTools.getAttributes(null, "DbConfig", "key", dbKey, "connUrl");

				String loginUser = FileTools.XmlTools.getAttributes(null, "DbConfig", "key", dbKey, "loginUser");

				String pwd = FileTools.XmlTools.getAttributes(null, "DbConfig", "key", dbKey, "pwd");

				Class.forName(driver);
				dbConn = DriverManager.getConnection(connUrl, loginUser, pwd);
				bs = true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return bs;
		}

		public static synchronized int Execute(String dbKey, Object sql, Object objs) throws Exception {

			if (!ini(dbKey)) {
				System.out.println("数据库初始化失败");
				return -1;
			}

			int count = 0;
			if (CheckTools.checkEmpty(sql)) {
				return 0;
			}

			String runSql = "";

			try {
				// 设置为手动提交
				dbConn.setAutoCommit(false);

				if (sql instanceof String) {
					runSql = (String) sql;
					ps = dbConn.prepareStatement(runSql);
					if (null != objs) {
						if (objs instanceof String) {
							if (((String) objs).trim().length() > 0) {
								ps.setObject(0, (String) objs);
							}
						} else if (objs instanceof List) {
							for (int i = 0; i < ((List) objs).size(); i++) {
								ps.setObject(i + 1, ((List) objs).get(i));
							}
						}
					}
					count += ps.executeUpdate();
				} else if (sql instanceof List) {

					if (((List) sql).size() > 0) {
						for (int i = 0; i < ((List) sql).size(); i++) {
							runSql = (String) ((List) sql).get(i);
							ps = dbConn.prepareStatement(runSql);
							if (null != objs) {
								if (objs instanceof String) {

									if (((String) objs).trim().length() > 0) {
										ps.setObject(0, (String) objs);
									}

								} else if (objs instanceof List) {
									for (int i2 = 0; i2 < ((List) objs).size(); i2++) {
										ps.setObject(i2 + 1, ((List) objs).get(i2));
									}
								}
							}
							count += ps.executeUpdate();
						}
					}
				}
				// 提交事务
				dbConn.commit();
				return count;
			} catch (Exception ex) {
				dbConn.rollback();// 某一条数据添加失败时，回滚
				ex.printStackTrace();
			} finally {
				close();
			}

			return count;
		}

		public static synchronized List<Map<String, Object>> Query(String dbKey, String sql, Object objs)
				throws Exception {

			if (!ini(dbKey)) {
				System.out.println("数据库初始化失败");
				return null;
			}

			List lst = new ArrayList();
			Map map = null;

			try {
				// 构建预处理
				ps = dbConn.prepareStatement(sql);

				if (objs != null) {
					if (objs instanceof String) {
						if (((String) objs).trim().length() > 0) {
							ps.setObject(0, (String) objs);
						}
					} else if (objs instanceof List) {
						for (int i2 = 0; i2 < ((List) objs).size(); i2++) {
							ps.setObject(i2 + 1, ((List) objs).get(i2));
						}
					}
				}

				rs = ps.executeQuery();
				if (rs != null) {
					rsd = rs.getMetaData();
					while (rs.next()) {
						int columnCount = rsd.getColumnCount();
						map = new HashMap();
						for (int i = 1; i <= columnCount; i++) {
							map.put(rsd.getColumnName(i), rs.getObject(i));
						}
						lst.add(map);
					}
				}
				rsd = null;
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				close();
			}
			// 返回数据集合
			return lst;
		}

	}

	public static class HttpTools {

		/**
		 * 向指定URL发送GET方法的请求
		 *
		 * @param url
		 *            发送请求的URL
		 * @param param
		 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
		 * @return URL 所代表远程资源的响应结果
		 */
		public static synchronized String sendGet(String url, Object param, FileCoding fileCoding) {
			String result = "";
			BufferedReader in = null;
			try {
				String urlNameString = url;
				if (Tools.CheckTools.checkNotEmpty(param)) {
					if (((String) param).length() > 0) {
						urlNameString += "?" + (String) param;
					}
				}

				URL realUrl = new URL(urlNameString);
				// 打开和URL之间的连接
				URLConnection connection = realUrl.openConnection();
				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("Charset", "UTF-8");
				if (Tools.CheckTools.checkNotEmpty(fileCoding)) {
					if (fileCoding.equals(FileCoding.GBK)) {
						connection.setRequestProperty("Charset", "GBK");
					} else if (fileCoding.equals(FileCoding.UTF8)) {
						connection.setRequestProperty("Charset", "UTF-8");
					}
				}

				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				// 建立实际的连接
				connection.connect();
				// 获取所有响应头字段
				Map<String, List<String>> map = connection.getHeaderFields();
				// 遍历所有的响应头字段
				for (String key : map.keySet()) {
					// System.out.println(key + "--->" + map.get(key));
				}
				// 定义 BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(connection.getInputStream(), fileCoding.getName()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}

			} catch (Exception e) {
				System.out.println("发送GET请求出现异常！" + e);
				e.printStackTrace();
			} // 使用finally块来关闭输入流
			finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
			return result;
		}

		/**
		 * 向指定 URL 发送POST方法的请求
		 *
		 * @param url
		 *            发送请求的 URL
		 * @param param
		 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
		 * @return 所代表远程资源的响应结果
		 */
		public static synchronized String sendPost(String url, Object param, FileCoding fileCoding) {
			PrintWriter out = null;
			BufferedReader in = null;
			String result = "";
			try {
				URL realUrl = new URL(url);
				// 打开和URL之间的连接
				URLConnection connection = realUrl.openConnection();
				// 设置通用的请求属性
				connection.setRequestProperty("accept", "*/*");
				connection.setRequestProperty("connection", "Keep-Alive");
				connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
				connection.setRequestProperty("Content-Type", "application/json");
				connection.setRequestProperty("Charset", "UTF-8");
				if (Tools.CheckTools.checkNotEmpty(fileCoding)) {
					if (fileCoding.equals(FileCoding.GBK)) {
						connection.setRequestProperty("Charset", "GBK");
					} else if (fileCoding.equals(FileCoding.UTF8)) {
						connection.setRequestProperty("Charset", "UTF-8");
					}
				}

				// 发送POST请求必须设置如下两行
				connection.setDoOutput(true);
				connection.setDoInput(true);
				// 获取URLConnection对象对应的输出流
				out = new PrintWriter(connection.getOutputStream());
				// 发送请求参数
				if (Tools.CheckTools.checkNotEmpty(param)) {
					out.print(param);
				}
				// flush输出流的缓冲
				out.flush();
				// 定义BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

				// 获取头部信息
				Map<String, List<String>> map = connection.getHeaderFields();

				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				return result;
			} catch (Exception e) {
				System.out.println("发送 POST 请求出现异常！" + e);
				e.printStackTrace();
			} // 使用finally块来关闭输出流、输入流
			finally {
				try {
					if (out != null) {
						out.close();
					}
					if (in != null) {
						in.close();
					}
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			return result;
		}
	}
	

	public static class MailTools {

		private static Properties pros = null;
		private static Authenticator auth = null;
		private static MimeMessage mimeMessage = null;
		private static BodyPart bodypart = null;

		private static boolean ini() {
			boolean bs = false;
			try {
				// 加载配置文件
				MailEntity.Server server = new MailEntity.Server();
				server.setSmtp(Tools.FileTools.PropertiesTools.getProperties("smtp"));
				server.setPort(Tools.FileTools.PropertiesTools.getProperties("port"));
				server.setNeedAuth(Tools.FileTools.PropertiesTools.getProperties("needAuth"));
				server.setUsername(Tools.FileTools.PropertiesTools.getProperties("username"));
				server.setPassword(Tools.FileTools.PropertiesTools.getProperties("password"));
				if ((Tools.FileTools.PropertiesTools.getProperties("hasSSL")).equals("true")) {
					server.setHasSSL(true);
				} else {
					server.setHasSSL(false);
				}

				pros = new Properties();
				pros.setProperty("mail.smtp.host", server.getSmtp());
				pros.setProperty("mail.smtp.auth", server.getNeedAuth());
				if (server.isHasSSL()) {
					pros.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
					pros.setProperty("mail.smtp.port", server.getPort());
					pros.setProperty("mail.smtp.socketFactory.port", server.getPort());
				}
				pros.setProperty("mail.user", server.getUsername());
				pros.setProperty("mail.password", server.getPassword());
				auth = new Email_Autherticator();
				Session session = Session.getDefaultInstance(pros, auth);
				session.setDebug(false); // 设置获取 debug 信息
				mimeMessage = new MimeMessage(session);
				bs = true;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return bs;
		}

		public static boolean send(MailEntity.Mails mails) {
			boolean bs = false;
			try {
				if (!ini()) {
					return false;
				}
				if (mails.getTo().size() == 0) {
					return false;
				}
				for (int i = 0; i < mails.getTo().size(); i++) {
					String address = mails.getTo().get(i).toString();
					mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
				}

				mimeMessage.setSubject(mails.getSubject());

				mimeMessage.setSentDate(new Date());
				mimeMessage.setFrom(new InternetAddress(pros.getProperty("mail.user"), mails.getFrom()));

				MimeMultipart mp = new MimeMultipart();
				// 正文
				MimeBodyPart content = new MimeBodyPart();
				content.setContent(mails.getText().toString(), "text/html;charset=gb2312");
				mp.addBodyPart(content);
				// 如果有附件
				List fujianList = mails.getFuJianPath();
				List fujianNameList = mails.getFuJianName();

				if (Tools.CheckTools.checkNotEmpty(fujianList) && Tools.CheckTools.checkNotEmpty(fujianNameList)) {
					if (fujianList.size() > 0) {
						for (int i = 0; i < fujianList.size(); i++) {
							MimeBodyPart fujian = new MimeBodyPart();
							// 添加附件
							DataSource source = new FileDataSource(fujianList.get(i).toString());
							// 添加附件的内容
							fujian.setDataHandler(new DataHandler(source));
							// 添加附件的标题
							// 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
							fujian.setFileName(MimeUtility.encodeText(fujianNameList.get(i).toString()));
							mp.addBodyPart(fujian);
						}

					}
				}

				// 将multipart对象放到message中
				mimeMessage.setContent(mp);
				mimeMessage.saveChanges();
				sendMessage();
				bs = true;
			} catch (Exception ex) {
				ex.printStackTrace();
				if (ex.getMessage().toString().equals("Invalid Addresses")) {
					System.out.println("Invalid Addresses");
					bs = true;
				} else {
					bs = false;
				}
			}
			return bs;
		}

		private static class Email_Autherticator extends Authenticator {

			public javax.mail.PasswordAuthentication getPasswordAuthentication() {
				String userName = pros.getProperty("mail.user");
				String password = pros.getProperty("mail.password");
				return new PasswordAuthentication(userName, password);
			}
		}

		private static void sendMessage() throws Exception {
			Transport.send(mimeMessage);
		}

	}

}
